<?php
/*
 * Session variables:
 * $_SESSION['database'] [string] = database name of the current tutorial centre
 * $_SESSION['type'] [string] = user type of the logged in user
 * $_SESSION['authorised'] [boolean] = whether or not the current user is logged in
 * $_SESSION['user'] [string] = the username/ email of the logged in user 
 * $_POST['oldpass'] [string] = the old password of the user
 * $_POST['newpass1'] [string] = the new password of the user
 * $_POST['newpass2'] [string] = for verification of the new password
 */ 
session_start();

if(isset($_POST['submit']) && isset($_SESSION['authorised']) && $_SESSION['authorised'] == true)
{
	$host = 'localhost';
	$dbuser = 'postgres';
	$dbpass = 'password';
	$dbname = $_SESSION['database'];
	pg_connect("host='$host' user='$dbuser' password='$dbpass' dbname='$dbname'") or die(pg_last_error());
	
	$username = $_SESSION['user'];
	$password2 = pg_escape_string($_POST['newpass2']);
	$password1 = pg_escape_string($_POST['newpass1']);
	
	$sql = "SELECT * FROM users where username = '$username';";
	$result = pg_query($sql);	
	$old_password = pg_fetch_result($result, 0, 'password');
	
	if ($old_password == $_POST['oldpass'] && $password1==$password2 && $password1!='')
	{
		$sql = "UPDATE users SET password = '$password1' where username = '$username'";
		$result = pg_query($sql);	
		$_SESSION['message'] = "Password successfully changed.";	
	}
	else
	{
		$_SESSION['message'] = "Password change unsuccessful. Old password incorrect.";
	}
	header('Location: changepassword.php');
}
else
{
	header("Location: index.php");
}
?>
